<?php

namespace app\admin\controller\autoplantemp;

use app\common\controller\Backend;
use fast\Tree;
use think\Db;

/**
 * 
 *
 * @icon fa fa-file
 */
class Autoplantemp extends Backend
{
    
    /**
     * Autoplantemp模型对象
     */
    protected $model = null;
    protected $noNeedRight=["lists","status","classeslist","classesdel"];
    protected $noNeedLogin=["lists","status","classeslist","classesdel"];


    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Autoplantemp');
        $this->modelValidate = true;
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where);
            $total = $total->where("status", "<>", -1);
            //if ($_SESSION['think']['admin']['group_id'] == 2) {
            //    $total = $total->where("city_id", "=", $_SESSION['think']['admin']['city_id']);
            //}
            $total = $total
                ->count();

            $list = $this->model
                ->where($where);
            //if ($_SESSION['think']['admin']['group_id'] == 2) {
            //    $list = $list->where("city_id", "=", $_SESSION['think']['admin']['city_id']);
            //}
            $list = $list->where("status", "<>", -1)
                ->order('weigh desc,id desc')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            //$this->model->getLastSql();
            $list = collection($list)->toArray();

//            $tree = Tree::instance();
//            $tree->init($list, 'pid');
//            $list = $tree->getTreeList($tree->getTreeArray(0), 'name');
//            $data = array();
//            for ($i = 0; $i < count($list); $i++) {
//                $v = $list[$i];
//                $data[] = [
//                    'id' => $v['id'],
//                    'parent' => $v['pid'] ? $v['pid'] : '#',
//                    'name' => $v['name'],
//                    'type' => $v['type'],
//                    'status' => $v['status'],
//                    'school_id' => model("School")->getSchool_idTextAttr($v['school_id'])
//                ];
//            }


            for($i=0;$i<count($list);$i++){
//                $list[$i]['province_id']=model('Cityarea')->getProvince_idTextAttr($list[$i]['province_id']);
//                $list[$i]['city_id']=model('Cityarea')->getCity_idTextAttr($list[$i]['city_id']);
//                $list[$i]['district_id']=model('Cityarea')->getDistrict_idTextAttr($list[$i]['district_id']);
//                $list[$i]['province_id']=preg_replace("/\/$/","",model('Cityarea')->getProvince_idTextAttr($list[$i]['province_id'])."/".$list[$i]['city_id']."/".$list[$i]['district_id']);
//                $list[$i]['school_id']=model('School')->getSchool_idTextAttr($list[$i]['school_id'],$list[$i]);
                //$v['classes_id']=$this->model->getClasses_idTextAttr($v['classes_id'],$v);
                $list[$i]['classes_id']=$this->model->getClasses_idTextAttr($list[$i]['classes_id'],$list[$i]);
                //$v['ocation_id']=$this->model->getOcation_idTextAttr($v['ocation_id'],$v);
                $list[$i]['ocation_id']=$this->model->getOcation_idTextAttr($list[$i]['ocation_id'],$list[$i]);
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
//        $this->assignconfig("relType",$_REQUEST['relType']);
//        $this->assignconfig("relId",$_REQUEST['relId']);
        $this->assignconfig("admin",$_SESSION['think']['admin']);
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $datatime=date("Y-m-d H:i:s");
                    $params['create_time']=$datatime;
                    unset($params['delete_time']);
                    unset($params['update_time']);
//                    if($_SESSION['think']['admin']['group_id']==2){
//                        $params['city_id']=$_SESSION['think']['admin']['city_id'];
//                    }
                    $params['date']=(!array_key_exists("date",$params)||$params['date']=="")?date("Y-m-d",time()):date("Y-m-d",strtotime($params['date']));
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assignconfig("admin",$_SESSION['think']['admin']);
        return $this->view->fetch();
    }


    /**
     * 保存班级到课程表
     */
    public function classesadd()
    {
        if ($this->request->isPost()) {
            $user=$this->auth->getUserInfo();
            $params = $this->request->post();
            $city_id = $user['city_id'];
            $params['table_id']=0;
            $classes_type = $this->request->param('classes_type', 1);
            $class_id = $this->request->param('classes_id', 0);
            if($this->request->param('class_id', 0)>0){
                $class_id=$this->request->param('class_id', 0);
            }
            if($classes_type==1){
                $params['table_id']=$this->request->param('table_id', 0);
                $params['publicwelfare_id']=null;
                $class_id=$class_id;
                $ocaiton_classes_id=null;
            }else{
                $params['publicwelfare_id']=$this->request->param('publicwelfare_id', 0);
                $params['table_id']=null;
                $ocaiton_classes_id=$class_id;
                $class_id=null;
            }
            // 获取POST参数
            $apply_type = $this->request->param('apply_type', 0);
            $t_id = $this->request->param('id', 0);
            $apply_id = $this->request->param('apply_id', 0);


            //print_r($this->request->param());exit;
            $teaching_point = $this->request->param('location_id', 0);
            if($this->request->param('teaching_point', 0)>0){
                $teaching_point=$this->request->param('teaching_point', 0);
            }
            $class_time = $this->request->param('class_time', '');
            $course_type = $this->request->param('course_type', 1);
            $fee = $this->request->param('fee', 0);
            $quota = $this->request->param('quota', 0);
            $params['classes_type'] = $classes_type;
            $params['class_id'] = $class_id;
            $params['teaching_point'] = $teaching_point;
            // 验证必填字段
            if (empty($params['class_id'])) {
                $this->error('班级ID不能为空');
            }
            if (empty($params['teaching_point'])) {
                $this->error('教学点不能为空');
            }
            if (empty($params['class_time'])) {
                $this->error('上课时间不能为空');
            }
    
            try {
    
            // 解析上课时间
            $datetime = new \DateTime($class_time);
            $date = $datetime->format('Y-m-d');
            $start_time = $datetime->format('H:i:s');
            
            // 计算结束时间（假设每节课1.5小时）
            $end_datetime = clone $datetime;
            $end_datetime->add(new \DateInterval('PT90M'));
            $end_time = $end_datetime->format('H:i:s');

            // 计算周几（1=周一，7=周日）
            $week = weekname($datetime->format('N'));
            
            // 获取班级信息
            if($params['classes_type']==2){
                $classInfo = Db::name('fa_ocation_class')->where('id', $params['class_id'])->find();
                if ($classInfo == null) {
                    $this->error('班级信息不存在');
                }
            }elseif($params['classes_type']==1) {
                $classInfo = Db::name('eb_classes')->where('id', $params['class_id'])->find();
                if ($classInfo == null) {
                    $this->error('班级信息不存在');
                }
            }
            if (!$classInfo) {
                return json(['code' => 0, 'msg' => '班级信息不存在']);
            }
            
            // 获取教学点信息
            $ocationInfo = Db::name('ocation')->where('id', $teaching_point)->find();
            if (!$ocationInfo) {
                return json(['code' => 0, 'msg' => '教学点信息不存在']);
            }
            $autoplanModel = new \app\admin\model\Autoplan();
            $timeSlots= [
                'year'=>$datetime->format('Y'),
                'month'=>$datetime->format('m'),
                'day'=>$datetime->format('d'),
                'startTime'=>$start_time,
                'endTime'=>$end_time,
            ];
            $autoplan = $autoplanModel->checkTimeslotOcationFormAutoplan($timeSlots, $teaching_point,$t_id);
            if(!empty($autoplan)){
                return json(['code' => 0, 'msg' => "该时间冲突，以下班级占用了当天的教室：<br><br>{$autoplan['class_name']}<br>教学点：{$autoplan['ocation_name']},<br>上课时间：{$autoplan['start_time']}至{$autoplan['end_time']}"]);
            }
            $parentOcations=model("\app\admin\model\Ocation")->getParentOcations($teaching_point);
            $parentTeachingOcationId=$parentOcations["parentTeachingOcationId"];
            $topTeachingOcationId=$parentOcations["topTeachingOcationId"];
            $areaTeachingOcationId=$parentOcations["areaTeachingOcationId"];

            // 准备插入数据
            $data = [
                't_id'=>0,
                'table_id' => $this->request->param('table_id', 0), // 从当前页面获取
                'apply_type' => $apply_type, // 从当前页面获取
                'apply_form_id' => $apply_id,
                'classes_id' => $class_id,
                'ocation_class_id' => $ocation_class_id ?? 0,
                'classes_type' => $classes_type,
                'city_id' => $city_id ?? 0,
                'ocation_class_id'=>$ocaiton_classes_id,
                'ocation_id' => $teaching_point,
                'addresslv_id'=>$parentTeachingOcationId ?? 0,
                'date' => $date,
                'week' => $week,
                'start_time' => $start_time,
                'end_time' => $end_time,
                'class_index' => 1, // 默认第1节课
                'teacher_id' => $classInfo['teacher_id'] ?? 0,
                'manager_id' => $classInfo['manager_id'] ?? 0,
                'subject_lv' => $classInfo['subject_lv'] ?? 0,
                'table_type' => $course_type,
                'oindex'=>1,
                'daytime'=>'上午',
                'parent_teaching_ocation_id'=>$parentTeachingOcationId,
                'top_teaching_ocation_id'=>$topTeachingOcationId,
                'area_teaching_ocation_id'=>$areaTeachingOcationId,
                'school_id'=>$classInfo['school_id'] ?? 0,
                'community_id'=>$classInfo['community_id'] ?? 0,
                'is_free' => $classInfo['price']>0?1:0,
                //'fee' => $fee,
                //'quota' => $quota,
                'bz'=>'从报名表班级导入生成',
                'status' => 1,
                'create_time' => time(),
                'update_time' => time()
            ];
            
            // 检查是否已存在相同记录
                if(!$t_id) {
                    $existing = Db::name('course_table_autoplan')
                        ->where([
                            'table_id' => $data['table_id'],
                            'classes_id' => $class_id,
                            'ocation_id' => $teaching_point,
                            'date' => $date,
                            'start_time' => $start_time
                        ])
                        ->find();
                }else{
                    $existing = Db::name('course_table_autoplan')
                        ->where([
                            'id'=>$t_id
                        ])->find();
                }
            
            if ($existing) {
                // 更新现有记录
                $data['update_time'] = time();
                $result = Db::name('course_table_autoplan')
                    ->where('id', $existing['id'])
                    ->update($data);
                    
                if ($result !== false) {
                    return json([
                        'code' => 1,
                        'msg' => '班级信息更新成功',
                        'data' => ['id' => $existing['id']]
                    ]);
                } else {
                    return json(['code' => 0, 'msg' => '更新失败']);
                }
            } else {
                // 插入新记录
                $data['id']=Db::name('course_table_autoplan')->max('id')+1;
                $result = Db::name('course_table_autoplan')->insert($data);
                if ($result) {
                    $insertId = Db::name('course_table_autoplan')->getLastInsID();
                    return json([
                        'code' => 1,
                        'msg' => '班级信息保存成功',
                        'data' => ['id' => $insertId]
                    ]);
                } else {
                    return json(['code' => 0, 'msg' => '保存失败']);
                }
            }  


            } catch (\Exception $e) {
                $this->error('保存失败：' . $e->getMessage());
            }
        }

    }

   public function classesdel(){
        $id=$this->request->param("id");
        $result=Db::name("course_table_autoplan")->where("id",$id)->delete();
        if($result){
            $this->success("删除成功");
        }else{
            $this->error("删除失败");
        }
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $datatime=date("Y-m-d H:i:s");
                    $params['update_time']=$datatime;
                    unset($params['delete_time']);
                    unset($params['create_time']);
//                    if($_SESSION['think']['admin']['group_id']==2){
//                        $params['city_id']=$_SESSION['think']['admin']['city_id'];
//                    }
                    $params['date']=(!array_key_exists("date",$params)||$params['date']=="")?date("Y-m-d",time()):date("Y-m-d",strtotime($params['date']));
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assignconfig("admin",$_SESSION['think']['admin']);
        $this->view->assign("row", $row);
        return $this->view->fetch();

    }

    /**
     * 添加
     */
    public function view($ids = NULL)
    {
        $row=$this->model->getRow($ids);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function lists($ids = NULL){
        $where="where 1=1";
        if($_SESSION['think']['admin']['group_id']!=1){
            $where.=" and city_id='{$_SESSION['think']['admin']['city_id']}'";
        }
        $page=1;
        $pagesize=50;
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                $keyField = $this->request->request("keyField");
                $keyValue = $this->request->request("keyValue");
                $page = $this->request->request("pageNumber");
                $page = ($page == null) ? 1 : $page;
                $pagesize = $this->request->request("pageSize");
                $pagesize = ($pagesize == null) ? 10 : $pagesize;
                if ($keyValue != "") {
                    $nn=preg_split("/\,/",$keyValue);
                    for($i=0;$i<count($nn);$i++) {
                        $where.= " and $keyField='{$nn[$i]}'";
                    }
                }
            }else{
                $where="where 1=1";
                if(isset($_REQUEST['city_id'])&&$_REQUEST['city_id']>0){
                    //$where.=" and city_id=".$_REQUEST['city_id'];
                }
            }
        }
        $sql="select id,date name from dev002_gxyusheng.fa_course_table_autoplan_temp $where limit " . (($page - 1) * $pagesize) . ",$pagesize";
        $list = db()->query($sql);

//        $r_name = model("School")->field("id,name")->where("id", "=", $_REQUEST['school_id'])->select();
//        if (empty($list)&&!empty($r_name)) {
//            $data = array(
//                "type" => "file",
//                "pid" => 0,
//                "name" => $r_name[0]['name']."学科",
//                "title" => $r_name[0]['name'],
//                "ismenu" => 0,
//                "createtime" => time(),
//                "updatetime" => time(),
//                "status" => 1,
//                "school_id" => $_REQUEST['school_id'],
//            );
//            $this->model->create($data);
//        }
//        $sql="select id,pid,name,title,status from dev002_gxyusheng.fa_course_table_autoplan_temp $where limit " . (($page - 1) * $pagesize) . ",$pagesize";
//        $list = db()->query($sql);
//        $tree = Tree::instance();
//        $tree->init($list, 'pid');
//        $list = $tree->getTreeList($tree->getTreeArray(0), 'name');

        $total = db()->query("select count(1) as c from  dev002_gxyusheng.fa_course_table_autoplan_temp $where")[0];
        echo json_encode(array("list" => $list, "total" => $total['c']));
        exit;
    }

    public function status($ids = '')
    {
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }
        try {
            $result=$this->model->where("id","=",$ids)->field("status")->find();
            $v=$result->status==1?0:1;
            $this->model->where("id","=",$ids)->update(["status"=>$v]);
            $this->success('切换成功!');
        } catch (\Exception $e) {
            $this->error('切换失败!'.$e->getMessage());
        }
    }

    public function changeStatus($ids = '')
    {
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }
        try {
            $result=$this->model->where("id","=",$ids)->field("status")->find();
            $v=$result->status==1?0:1;
            $this->model->where("id","=",$ids)->update(["status"=>$v]);
            $this->success('切换成功!');
        } catch (\Exception $e) {
            $this->error('切换失败!'.$e->getMessage());
        }
    }




    /**
     * 获取班级列表数据
     * 用于ajax动态加载班级信息
     */
    public function classeslist()
    {
        if ($this->request->isAjax() || $this->request->isGet()) {
            $apply_id = $this->request->param('apply_id', 0);
            $apply_type = $this->request->param('apply_type', 1);
            if (empty($apply_id)) {
                return json([
                    'code' => 0,
                    'msg' => 'apply_id参数不能为空',
                    'data' => []
                ]);
            }
            
            try {

                $joinTable = 'eb_classes c';
                if ($apply_type == 2) {
                    $joinTable = 'OcationClass c';
                }

                // 查询课程表自动排课数据
                $list = Db::name('course_table_autoplan')
                    ->alias('cta')
                    ->field([
                        'cta.id',
                        'cta.classes_id',
                        'cta.ocation_id as location_id',
                        'cta.date',
                        'cta.start_time',
                        'cta.end_time',
                        'cta.table_type as course_type',
                        'c.price fee',
                        'c.num quota',
                        'cta.date class_time',
                        'cta.apply_form_id',
                        'cta.apply_type',
                        'cta.status',
                        'cta.create_time',
                        'cta.update_time'
                    ])
                    ->join($joinTable, 'cta.classes_id = c.id', 'LEFT')
                    ->where('cta.apply_form_id', $apply_id)
                    ->where('cta.bz', '从报名表班级导入生成')
                    ->where('cta.status', '<>', -1)
                    ->order('cta.date asc,cta.start_time asc,cta.id')
                    ->select();
                
                $result = [];
                foreach ($list as $item) {
                    // 构造上课时间字符串
                    $class_time = '';
                    if (!empty($item['date']) && !empty($item['start_time'])) {
                        $class_time = $item['date'] . ' ' . $item['start_time'];
                        if (!empty($item['end_time'])) {
                            $class_time .= '-' . $item['end_time'];
                        }
                    }
                    
                    $result[] = [
                        'id' => $item['id'],
                        'class_id' => $item['classes_id'],
                        'location_id' => $item['location_id'],
                        'class_time' => $class_time,
                        'course_type' => $item['course_type'] ?: '1',
                        'fee' => $item['fee'] ?: '',
                        'quota' => $item['quota'] ?: '',
                        'apply_form_id' => $item['apply_form_id'],
                        'apply_type' => $item['apply_type'],
                        'status' => $item['status'],
                        'create_time' => $item['create_time'],
                        'update_time' => $item['update_time']
                    ];
                }
                
                return json([
                    'code' => 1,
                    'msg' => '获取成功',
                    'data' => $result,
                    'count' => count($result)
                ]);
                
            } catch (\Exception $e) {
                return json([
                    'code' => 0,
                    'msg' => '获取班级数据失败：' . $e->getMessage(),
                    'data' => []
                ]);
            }
        }
        
        return json([
            'code' => 0,
            'msg' => '请求方式错误',
            'data' => []
        ]);
    }

}